package com.jessechanrui.template.thread.threadlocal;

import com.jessechanrui.template.thread.ThreadUtil;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author chenrui
 * @date 2024/12/26
 */
public class ThreadLocalCase {

    //定义线程本地变量
    private static final ThreadLocal<Foo> LOCAL_FOO = new ThreadLocal<Foo>();

    public static void main(String[] args) {

        //获取自定义的混合型线程池
        ThreadPoolExecutor threadPool = ThreadUtil.getMixedTargetThreadPool();
        for (int i = 0; i < 5; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //获取“线程本地变量” 中当前线程所绑定的值
                    if (LOCAL_FOO.get() == null) {
                        //设置“线程本地变量” 中当前线程所绑定的值
                        LOCAL_FOO.set(new Foo());
                    }
                    ThreadUtil.print("本地初始值：" + LOCAL_FOO.get());
                    for (int j = 0; j < 10; j++) {
                        Foo foo = LOCAL_FOO.get();
                        foo.setBar(foo.getBar() + 1);
                        ThreadUtil.sleep(10);
                    }
                    ThreadUtil.print("累加后数值：" + LOCAL_FOO.get());
                    //删除“线程本地变量” 中当前线程所绑定的值; 该部分对线程池中的线程尤其重要； 防止内存泄漏
//                    LOCAL_FOO.remove();
                }
            });
        }
    }
}
